
#include "delay.h"
#include <stm32f10x.h>

void delay_init() {
    // 72MHz/8=9	AHB/8 = 9MHz
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
}

static void delay_times(unsigned long ts) {

    SysTick->LOAD = ts;
    // clear val，不被上次的值影响
    SysTick->VAL = 0;

    //开始计数
    SysTick->CTRL |= 1;

    //等待计数完成,block
    while ((SysTick->CTRL & 1 << 16) == 0)
        ;

    // stop timer
    SysTick->CTRL &= ~1;
}

void delay_1s() {
    // 1S计数9000000次
    delay_times(9000000);
}

void delay_1ms() {
    // 1ms计数9000次
    delay_times(9000);
}

void delay_1us() {
    // 1us计数9次
    delay_times(9);
}

void delay_s(unsigned long t) {
    while (t--) {
        delay_1s();
    }
}

void delay_ms(unsigned long t) {
    while (t--) {
        delay_1ms();
    }
}

void delay_us(unsigned long t) {
    while (t--) {
        delay_1us();
    }
}
